"""
数据库设置脚本
用于初始化数据库并填充示例数据
"""

from app import app, db
from models import Book, Publisher, SalesData, Inventory, Review, Logistics, BookCategory, BookTag
from datetime import datetime

def setup_database():
    with app.app_context():
        try:
            # 创建所有表
            db.create_all()
            print("✅ 数据库表创建成功!")
            
            # 检查是否已有数据
            if Book.query.first() is not None:
                print("数据库中已有数据，跳过填充")
                return

            # 创建出版社数据
            publishers_data = [
                {"name": "人民出版社", "address": "北京市", "contact": "010-xxxxxxx"},
                {"name": "商务印书馆有限公司", "address": "北京市", "contact": "010-xxxxxxx"},
                {"name": "学习出版社", "address": "北京市", "contact": "010-xxxxxxx"},
                {"name": "南海出版公司", "address": "海南省海口市", "contact": "0898-xxxxxxx"},
                {"name": "贵州人民出版社", "address": "贵州省贵阳市", "contact": "0851-xxxxxxx"},
                {"name": "上海人民出版社", "address": "上海市", "contact": "021-xxxxxxx"},
                {"name": "高等教育出版社", "address": "北京市", "contact": "010-xxxxxxx"},
                {"name": "中华书局", "address": "北京市", "contact": "010-xxxxxxx"},
                {"name": "中国人民大学出版社", "address": "北京市", "contact": "010-xxxxxxx"},
                {"name": "社会科学文献出版社", "address": "北京市", "contact": "010-xxxxxxx"}
            ]
            
            publishers = []
            for pub_data in publishers_data:
                publisher = Publisher(**pub_data)
                db.session.add(publisher)
                publishers.append(publisher)
            
            db.session.commit()
            print(f"✅ 已创建 {len(publishers)} 个出版社")

            # 创建图书数据
            books_data = [
                {
                    "title": "党的十九19大报告辅导读本+中国共产党章程 全2册",
                    "isbn": "9787010184272",
                    "authors": "中共中央宣传部",
                    "publish_date": "2017年10月",
                    "price": "￥37.00",
                    "hot_index": 9.85
                },
                {
                    "title": "中国党第十九次全国代表大会文件汇编",
                    "isbn": "9787010184326",
                    "authors": "中共中央宣传部",
                    "publish_date": "2017年10月",
                    "price": "￥12.00",
                    "hot_index": 9.83
                },
                {
                    "title": "全面从严治党面对面",
                    "isbn": "9787514707663",
                    "authors": "中共中央宣传部理论局",
                    "publish_date": "2017年03月",
                    "price": "￥19.80",
                    "hot_index": 9.68
                },
                {
                    "title": "现代汉语词典(第7版)",
                    "isbn": "9787100124508",
                    "authors": "中国社会科学院语言研究所词典编辑室",
                    "publish_date": "2016年09月",
                    "price": "￥109.00",
                    "hot_index": 9.66
                },
                {
                    "title": "解忧杂货店",
                    "isbn": "9787544270878",
                    "authors": "(日)东野圭吾",
                    "publish_date": "2014年05月",
                    "price": "￥39.50",
                    "hot_index": 9.65
                },
                {
                    "title": "追风筝的人",
                    "isbn": "9787208061644",
                    "authors": "[美]卡勒德·胡赛尼",
                    "publish_date": "2006年05月",
                    "price": "￥29.00",
                    "hot_index": 9.62
                },
                {
                    "title": "天才在左疯子在右（完整版）",
                    "isbn": "9787550263932",
                    "authors": "高铭",
                    "publish_date": "2016年01月",
                    "price": "￥39.80",
                    "hot_index": 9.59
                },
                {
                    "title": "新华字典（第11版）（双色本）",
                    "isbn": "9787100077040",
                    "authors": "中国社会科学院语言研究所",
                    "publish_date": "2011年06月",
                    "price": "￥24.90",
                    "hot_index": 9.58
                },
                {
                    "title": "神奇校车·图画书版（全11册）",
                    "isbn": "21005473",
                    "authors": "(美)乔安娜柯尔",
                    "publish_date": "2011年01月",
                    "price": "￥132.00",
                    "hot_index": 9.56
                },
                {
                    "title": "这就是二十四节气",
                    "isbn": "9787511026118",
                    "authors": "高春香，邵敏",
                    "publish_date": "2015年09月",
                    "price": "￥100.00",
                    "hot_index": 9.53
                }
            ]
            
            books = []
            for book_data in books_data:
                book = Book(**book_data)
                db.session.add(book)
                books.append(book)
            
            db.session.commit()
            print(f"✅ 已创建 {len(books)} 本图书")

            # 添加库存信息
            for i, book in enumerate(books):
                inventory = Inventory(
                    book_id=book.id,
                    quantity=1000 - i * 50  # 模拟不同库存量
                )
                db.session.add(inventory)
            
            # 添加分类信息
            categories = ["政治", "文学", "教育", "儿童", "工具书", "小说"]
            for i, book in enumerate(books):
                category = BookCategory(
                    book_id=book.id,
                    category=categories[i % len(categories)]
                )
                db.session.add(category)
            
            # 添加标签
            tags_data = [
                ["政治", "理论", "学习"],
                ["政治", "文件", "十九大"],
                ["政治", "党建", "从严治党"],
                ["工具书", "汉语", "词典"],
                ["小说", "外国文学", "治愈"],
                ["小说", "外国文学", "经典"],
                ["心理学", "精神病学", "故事"],
                ["工具书", "汉语", "字典"],
                ["儿童", "科普", "图画书"],
                ["儿童", "传统文化", "节气"]
            ]
            
            for i, book in enumerate(books):
                for tag_name in tags_data[i]:
                    tag = BookTag(
                        book_id=book.id,
                        tag=tag_name
                    )
                    db.session.add(tag)
            
            db.session.commit()
            print("✅ 数据填充完成!")
            
        except Exception as e:
            print(f"❌ 数据库设置失败: {e}")
            raise e

if __name__ == '__main__':
    setup_database()